package com.liuhongwei.test.builder.strategy.impl;


import com.liuhongwei.test.bean.Constants;
import com.liuhongwei.test.bean.FieldInfo;
import com.liuhongwei.test.bean.TableInfo;
import com.liuhongwei.test.builder.BuildExtendMapperXml;
import com.liuhongwei.test.builder.strategy.inf.MapperXmlStrategy;

import java.io.BufferedWriter;
import java.io.IOException;

/**
 * 扩展查询条件
 */
public class XmlFieldBaseQueryConditionExtendImpl implements MapperXmlStrategy {

    @Override
    public void generateMapperXml(TableInfo tableInfo, BufferedWriter bw) throws IOException {
        bw.write("\t<!--扩展查询条件-->\n");
        bw.write("\t<sql id=\"" + BuildExtendMapperXml.BASE_QUERY_CONDITION_EXTEND + "\">\n");
        for (FieldInfo field : tableInfo.getFieldExtendList()) {
            String propertyName = BuildExtendMapperXml.SELECT_PREFIX + field.getPropertyName();
            String fieldName = field.getFieldName();
            String str = "and " + fieldName + " like concat('%', #{" + propertyName + "}, '%')";
            String type = field.getSqlType();
//            if (Constants.SQL_DATE_TIME_TYPES.contains(type) || Constants.SQL_DATE_TYPES.contains(type)) {
//                if (propertyName.endsWith(Constants.SUFFIX_BEAN_QUERY_TIME_START)) {
//                    str = "<![CDATA[ and " + fieldName + " >= str_to_date(#{" + propertyName + "}, '%Y-%m-%d')]]>";
//                } else {
//                    str = "<![CDATA[ and " + fieldName + " < date_sub(str_to_date(#{" + propertyName
//                            + "}, '%Y-%m-%d'), interval -1 day)]]>";
//                }
//            }
            if (Constants.SQL_DATE_TIME_TYPES.contains(type) || Constants.SQL_DATE_TYPES.contains(type)) {
                if (propertyName.endsWith(Constants.SUFFIX_BEAN_QUERY_TIME_START)) {
                    str = "<![CDATA[ and " + fieldName + " >= #{" + propertyName + "}]]>";
                } else {
                    str = "<![CDATA[ and " + fieldName + " < #{" + propertyName + "}]]>";
                }
                bw.write("\t\t<if test=\"" + propertyName + " != null \">\n");
                bw.write("\t\t\t" + str + "\n");
                bw.write("\t\t</if>\n");
            }else {
                bw.write("\t\t<if test=\"" + propertyName + " != null and " + propertyName + " != ''\">\n");
                bw.write("\t\t\t" + str + "\n");
                bw.write("\t\t</if>\n");
            }

        }
        bw.write("\t</sql>\n\n");
    }
}
